package com.hcb.tonguetiphealth.widget.recommendhealth;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextPaint;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.GeneralPageAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.manager.TextViewShowHtmlManager;
import com.hcb.tonguetiphealth.model.Cate;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.MoreActivity;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class RecommendHealthCateInfoWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "RecommendHealthCateInfoWidget";
	private String url = Global.URL + Global.servlet_recommendCateInfo;
	private String url_MsgPhone = Global.URL + Global.servlet_recommendCateMsgPhone;
	
	private Activity ctx;
	private LayoutInflater inflater;
	private Handler mHandler;
	private Cate crrentCate;
	private List<Cate> cateList;
	private ImageView iv, iv1, iv2, iv3, iv4, iv5, iv6, iv_info, iv_explain;
	
	private TextView name, priceTip, server, cate_info, cate_situation, cate_explain, cate_addr;
	private RatingBar ratingBar;
	private Button bt_buy, bt_share, bt_mesphone;
	private LinearLayout bt_back, bt_comment, ll_info, ll_info_tv, ll_explain, ll_explain_tv;
	
	private int crrentPageId = 0;
	private ViewPager viewPager;
	private List<View> pageViews;
	private View view;
	private GeneralPageAdapter pageAdapter;
	
	private AlertDialog dalog;
	
	public RecommendHealthCateInfoWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		crrentCate = (Cate)ctx.getIntent().getSerializableExtra("cate");
		cateList = Global.cateList;
				
		inflater = ctx.getLayoutInflater();
		inflate(context, R.layout.recommend_health_cate_info, this); 
		
		iv = (ImageView)findViewById(R.id.recommend_health_cate_info_main_img);
		name = (TextView)findViewById(R.id.recommend_health_cate_info_name_textview);
		TextPaint tp = name.getPaint(); 
		tp.setFakeBoldText(true); 
		priceTip = (TextView)findViewById(R.id.recommend_health_cate_info_price_textview);
		server = (TextView)findViewById(R.id.recommend_health_cate_server_textview);
		ratingBar = (RatingBar)findViewById(R.id.recommend_health_cate_info_ratings_ratingbar);
		
		bt_back = (LinearLayout)findViewById(R.id.recommend_health_cate_info_back_button);
		bt_comment = (LinearLayout)findViewById(R.id.recommend_health_cate_info_comment_button);
		bt_buy = (Button)findViewById(R.id.recommend_health_cate_info_buy_now_button);
		bt_share = (Button)findViewById(R.id.recommend_health_cate_info_share_button);
		bt_mesphone = (Button)findViewById(R.id.recommend_health_cate_mesphone_button);//10223
		ll_info = (LinearLayout)findViewById(R.id.recommend_health_cate_info_linearlayout_button);
		ll_info_tv = (LinearLayout)findViewById(R.id.recommend_health_cate_info_linearlayout);
		ll_explain = (LinearLayout)findViewById(R.id.recommend_health_cate_info_exlpain_linearlayout_button);
		ll_explain_tv = (LinearLayout)findViewById(R.id.recommend_health_cate_info_exlpain_linearlayout);
		iv_info = (ImageView)findViewById(R.id.recommend_health_cate_info_img);
		iv_explain = (ImageView)findViewById(R.id.recommend_health_cate_info_exlpain_img);
		cate_info = (TextView)findViewById(R.id.recommend_health_cate_info_textview);
		cate_situation = (TextView)findViewById(R.id.recommend_health_cate_situation_textview);
		cate_addr = (TextView)findViewById(R.id.recommend_health_cate_shopaddr_textview);
		cate_explain = (TextView)findViewById(R.id.recommend_health_cate_info_exlpain_textview);
		
		bt_back.setOnClickListener(this);
		bt_comment.setOnClickListener(this);
		bt_buy.setOnClickListener(this);
		bt_share.setOnClickListener(this);
		bt_mesphone.setOnClickListener(this);
		ll_info.setOnClickListener(this);
		ll_explain.setOnClickListener(this);
		
		viewPager = (ViewPager)findViewById(R.id.drinks_book_drink_info_viewpager);
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在登陆...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					dismissMessageDialog();
					break;
				case MessageWhat.GETWINEINFO_SUCCEED:
					initCateInfo();
					break;
				case MessageWhat.GETWINEINFO_FAILED:
					initCateInfo();
					break;
				case MessageWhat.MSG_SEND_ING:
					showMessageDialog(ctx, "发送短信到手机...");
					break;
				case MessageWhat.MSG_SEND_SUCCEED:
					showMessage(ctx, "短信发送成功");
					dismissMessageDialog();
					break;
				case MessageWhat.MSG_SEND_FAILD:
					showMessage(ctx, "短信发送失败");
					dismissMessageDialog();
					break;
				}
			}
			
		};
		initcurrentDrinks();
		initDataPageView();
	}
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.recommend_health_cate_info_back_button:
			ctx.setContentView(new RecommendHealthWidget(ctx));
			break;
		case R.id.recommend_health_cate_info_comment_button:

			break;
		case R.id.recommend_health_cate_info_buy_now_button:
			if(Global.user == null) {
				login();
			} else {
				ctx.getIntent().putExtra("cate", crrentCate);
				ctx.setContentView(new RecommendHealthCateBuyWidget(ctx));
			}
			break;
		case R.id.recommend_health_cate_info_share_button:
			if(Global.user == null) {
				login();
			} else {
				Intent intent = new Intent(ctx, MoreActivity.class);
				intent.putExtra("do", "share");
				ctx.startActivity(intent);
			}
			break;
		case R.id.recommend_health_cate_mesphone_button:
			if(Global.user == null) {
				login();
			} else {
				showTelDialog();
			}
			break;
		case R.id.recommend_health_cate_info_linearlayout_button:
			if(ll_info_tv.getVisibility() == LinearLayout.GONE) {
				ll_info_tv.setVisibility(LinearLayout.VISIBLE);
				iv_info.setBackgroundResource(R.drawable.list_more_up);
			} else {
				ll_info_tv.setVisibility(LinearLayout.GONE);
				iv_info.setBackgroundResource(R.drawable.list_more);
			}
			break;
		case R.id.recommend_health_cate_info_exlpain_linearlayout_button:
			if(ll_explain_tv.getVisibility() == LinearLayout.GONE) {
				ll_explain_tv.setVisibility(LinearLayout.VISIBLE);
				iv_explain.setBackgroundResource(R.drawable.list_more_up);
			} else {
				ll_explain_tv.setVisibility(LinearLayout.GONE);
				iv_explain.setBackgroundResource(R.drawable.list_more);
			}
			break;
		default:
			initCateInfo(v.getId());
			break;
		}
	}
	private void initCateInfo(int id) {
		int num = 0;
		switch(id) {
		case R.id.drinks_book_drink_info_pageview_img1:
			num += 0;
			break;
		case R.id.drinks_book_drink_info_pageview_img2:
			num += 1;
			break;
		case R.id.drinks_book_drink_info_pageview_img3:
			num += 2;
			break;
		case R.id.drinks_book_drink_info_pageview_img4:
			num += 3;
			break;
		case R.id.drinks_book_drink_info_pageview_img5:
			num += 4;
			break;
		case R.id.drinks_book_drink_info_pageview_img6:
			num += 5;
			break;
		}
		int position = crrentPageId*6 + num;
		Cate cate = cateList.get(position);
		if(cate.isCurrent()) {
			showMessage(ctx, "已是当前套餐详情");
		} else {
			crrentCate.setCurrent(false);
			crrentCate = cate;
			crrentCate.setCurrent(true);
			
			downLoadData();
		}
	}
	private void initCateInfo() {
		loadImage(iv, crrentCate.getImgURL());
		name.setText(crrentCate.getName());
		priceTip.setText(crrentCate.getPrice());
		ratingBar.setRating(crrentCate.getLevel());
		
		server.setText(crrentCate.getServer());
		TextViewShowHtmlManager.show(cate_info, crrentCate.getInfo());
		TextViewShowHtmlManager.show(cate_explain, crrentCate.getConsumeExplain());
		cate_situation.setText(crrentCate.getSituation());
		cate_addr.setText(crrentCate.getShopAddr());
	}
	private void downLoadData() {
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("cateId", crrentCate.getId()));
					response = HttpUtils.Post(url, params);
					if(Global.DEBUG) { 
						System.out.println(crrentCate.getId() + " -----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						JSONArray jList = jManager.getJsonList();
						if(null == jList) {
							
						} else {
							for(int i=0; i< jList.length(); i++) {
								JSONObject jObject = getJSONObject(jList, i);
								if(null != jObject) {
									crrentCate.setLevel(StringUtils.parseFloat(getString(jObject, "level")));
									crrentCate.setServer(getString(jObject, "fwsh")); 
									crrentCate.setConsumeExplain(getString(jObject, "xfsm")); 
									crrentCate.setInfo(getString(jObject, "tcnr")); 
									crrentCate.setShopAddr(getString(jObject, "fwdz")); 
									crrentCate.setSituation(getString(jObject, "shcs")); 
								}
							}
						}
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
				mHandler.sendEmptyMessage(MessageWhat.GETWINEINFO_SUCCEED);
			}
		}.start();
	}
	private void showTelDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
        dalog = builder.create();
     // 获取自定义布局  
    	LayoutInflater inflater = LayoutInflater.from(ctx);  
    	View view = inflater.inflate(R.layout.tel_edittext_dialog, null);  
    	final EditText et = (EditText)view.findViewById(R.id.tel_edittext_dialog_et);
    	et.setText(Global.user.getTel());
        et.setSelection(et.getText().length());
    	Button ok = (Button)view.findViewById(R.id.tel_edittext_dialog_ok_bt);
    	Button cancel = (Button)view.findViewById(R.id.tel_edittext_dialog_cancel_bt);
    	ok.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String tel = et.getText().toString();
				if(IsValidMobileNo(tel)) {
					dalog.dismiss();
					sendMsgToPhone(tel);
				} else {
					showMessage(ctx, "请输入正确的手机号码");
				}
			}
		});
    	cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				dalog.dismiss();
			}
		});
        dalog.setTitle("请输入电话号码");
		dalog.setView(view);
        dalog.show();
	}
	private void sendMsgToPhone(final String tel) {
		mHandler.sendEmptyMessage(MessageWhat.MSG_SEND_ING);
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("userId", Global.user.getUserId()));
					params.add(new BasicNameValuePair("cateId", crrentCate.getId()));
					params.add(new BasicNameValuePair("tel", tel));
					response = HttpUtils.Post(url_MsgPhone, params);
					if(Global.DEBUG) { 
						System.out.println(" -----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
						mHandler.sendEmptyMessage(MessageWhat.MSG_SEND_SUCCEED);
					} else {
						mHandler.sendEmptyMessage(MessageWhat.MSG_SEND_FAILD);
					}
				} else {
					mHandler.sendEmptyMessage(MessageWhat.MSG_SEND_FAILD);
				}
			}
		}.start();
	}
	private void initcurrentDrinks() {
		if(null != crrentCate) {
			loadImage(iv, crrentCate.getImgURL());
			name.setText(crrentCate.getName());
			priceTip.setText(crrentCate.getPrice());
			ratingBar.setRating(crrentCate.getLevel());
		}
	}
	private void initDataPageView() {
		for(Cate cate : cateList) {
			if(cate.isCurrent()) {
				crrentCate = cate;
				downLoadData();
				break;
			}
		}
		pageViews = new ArrayList<View>();
		int pageCount = cateList.size()/6 + (cateList.size()%6 == 0?0:1);
		pageCount = pageCount>4? 4 : pageCount;
		for(int i=0; i< pageCount; i++) {
			pageViews.add(inflater.inflate(R.layout.drinks_book_drinks_info_pageview, null));
		}
		
		Cate cate;
		
		for(int i=0; i<pageViews.size(); i++) {
			view = pageViews.get(i);
			iv1 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img1);
			iv2 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img2);
			iv3 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img3);
			iv4 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img4);
			iv5 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img5);
			iv6 = (ImageView)view.findViewById(R.id.drinks_book_drink_info_pageview_img6);
			int count = cateList.size() - (i+1)*6;
			if(count >= 0) {
				for(int j=1; j<=6; j++) {
					cate = cateList.get(i*6 + j-1);
					initImage(j, cate);
				}
			} else {
				count = cateList.size() - i*6;
				for(int j=1; j<=count; j++) {
					cate = cateList.get(i*6 + j-1);
					initImage(j, cate);
				}
				switch(count) {
				case 1:
					iv2.setVisibility(ImageView.INVISIBLE);
					iv3.setVisibility(ImageView.INVISIBLE);
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 2:
					iv3.setVisibility(ImageView.INVISIBLE);
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 3:
					iv4.setVisibility(ImageView.INVISIBLE);
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 4:
					iv5.setVisibility(ImageView.INVISIBLE);
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				case 5:
					iv6.setVisibility(ImageView.INVISIBLE);
					break;
				}
			}
			
		}
		
		pageAdapter = new GeneralPageAdapter(pageViews);
		viewPager.setAdapter(pageAdapter);
		viewPager.setOnPageChangeListener(new GuidePageChangeListener());
	}
	private void initImage(int id, Cate cate) {
		switch(id) {
		case 1:
			loadImage(iv1, cate.getImgURL());
			iv1.setOnClickListener(this);
			break;
		case 2:
			loadImage(iv2, cate.getImgURL());
			iv2.setOnClickListener(this);
			break;
		case 3:
			loadImage(iv3, cate.getImgURL());
			iv3.setOnClickListener(this);
			break;
		case 4:
			loadImage(iv4, cate.getImgURL());
			iv4.setOnClickListener(this);
			break;
		case 5:
			loadImage(iv5, cate.getImgURL());
			iv5.setOnClickListener(this);
			break;
		case 6:
			loadImage(iv6, cate.getImgURL());
			iv6.setOnClickListener(this);
			break;
		}
	}
	// 指引页面更改事件监听器
	class GuidePageChangeListener implements OnPageChangeListener {

		public void onPageScrollStateChanged(int arg0) {
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageSelected(int arg0) {
			crrentPageId = arg0;
			switch(arg0) {
			case 0:
				break;
			case 1:
				break;
			case 2:
				break;
			}
		}
	}
	@Override
	public void notifyAdapter() {
		
	}
}
